package net.bat.service.cb;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import net.bat.db.BaseDAOImpl;
import net.bat.pt.BObj;
import net.bat.upload.uploadServlet;
import net.bat.util.Cfg;
import net.cs.um.UMService;
import net.sk.pt.State;
import net.sk.pt.StateUtil;
import net.sk.web.StateCenter;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import dao.hb.NImage;
import dao.hb.UUser;

public class CBNImage implements IHandleHook {

	@Override
	public void beforeHandle(char method, HashMap<String, Object> psMap,
			HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub

	}
	private void moveFile(NImage rti,int uid,BaseDAOImpl dao) throws IOException{
		String uri = rti.getUri();
		int pos = uri.lastIndexOf(".");
		String uri_new = "["+uid+"_image]"+rti.getId()+uri.substring(pos);
		rti.setUri(uri_new);
		File f = uploadServlet.moveFile(uri,uri_new);
		rti.setFsize((int)f.length());
		Date dt = new Date();
		rti.setDtModify(dt);
		dao.update(rti);
		//写入时间戳索引
		uploadServlet.appendIndex(uid,'U',f);
	}
/**
 * 对临时上传文件进行处理
 */
	@Override
	public void afterHandle(char method, HashMap<String, Object> psMap,
			HttpServletRequest request, Object result) throws Exception {
		// TODO Auto-generated method stub
		BObj[] objs = (BObj[])psMap.get("objs");
		UUser usr = UMService.getUserBySession(request);
		int uid = usr.getId();
		BaseDAOImpl bdi = (BaseDAOImpl) Cfg.getBean("BaseDAOImpl");
		
		Object[][] rt = (Object[][] )result;
		for(int i=0; i<objs.length; i++){
			NImage rti = (NImage)rt[i][0];
			String uri = rti.getUri();
			//临时文件
			if(uri.startsWith("_")){
				moveFile(rti,uid,bdi);
			}
		}		

	}

}
